package com.github.bryx.workflow.dto.runtime;

import com.alibaba.fastjson.JSONObject;
import com.github.bryx.workflow.domain.WorkflowDefField;
import com.github.bryx.workflow.domain.WorkflowDefProcessConfig;
import com.github.bryx.workflow.domain.WorkflowInstanceActivity;
import com.github.bryx.workflow.util.CollectionsUtil;
import com.google.common.base.Functions;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author jameswu
 * @Date 2021/6/10
 **/
@Data
@Builder
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class CreateWorkflowInstanceActivityDto {
    @ApiModelProperty(value = "实例id")
    String workflowInstanceId;

    @ApiModelProperty(value = "任务id")
    String workflowTaskName;

    @ApiModelProperty(value = "流程task id")
    String workflowTaskId;

    @ApiModelProperty(value = "操作人id")
    String operatorId;

    @ApiModelProperty(value = "操作名称")
    String operateName;

    @ApiModelProperty(value = "操作描述")
    String description;

    @ApiModelProperty(value = "时间内容")
    @Builder.Default
    WorkflowInstanceActivity.ActivityContent content = new WorkflowInstanceActivity.ActivityContent();


    private void addFormField(String name, Object value){
        WorkflowInstanceActivity.FormField formField = new WorkflowInstanceActivity.FormField();
        formField.setName(name);
        formField.setValue(value);
        this.content.getFormFields().add(formField);
    }

    public void extractActivityFormData(String taskDefId, WorkflowDefProcessConfig processConfig, JSONObject formData){
        if (!processConfig.getUserTasks().containsKey(taskDefId)){
            return;
        }
        WorkflowDefProcessConfig.FormConfig formDef = processConfig.getUserTasks().get(taskDefId).getForm();
        List<WorkflowDefField> activityFields = formDef.getFields().stream().filter(field -> field.getActivity() != null && field.getActivity()).collect(Collectors.toList());
        if (CollectionsUtil.isNotEmpty(activityFields)){
            Map<String, WorkflowDefField> formFieldDefs = processConfig.getForm().getFields().stream().collect(Collectors.toMap(WorkflowDefField::getId, Functions.identity()));
            activityFields.forEach(field->{
                if (formData.get(field.getId())!=null){
                    this.addFormField(formFieldDefs.get(field.getId()).getDisplayName(), formData.get(field.getId()));
                }
            });
        }
    }

}
